mod ai_client;
mod config;
use ai_client::{send_chat_request, Message};
use std::error::Error;
use chrono::Local;
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    // 获取当前本地时间并格式化为字符串
    let local_time = Local::now();
    let local_str = local_time.format("%Y-%m-%d-%H-%M-%S").to_string();
    let app_log = format!("app_{}.log", local_str); 
    env_logger::Builder::from_default_env()
        .filter_level(log::LevelFilter::Info)
        .target(env_logger::Target::Pipe(Box::new(std::fs::File::create(app_log).unwrap())))
        .init();
    log::info!("Application started");

    loop {
        println!("请输入您的问题（输入 'exit' 退出）：");
        let mut input = String::new();
        std::io::stdin().read_line(&mut input).expect("读取输入失败");
        let input = input.trim();

        if input == "exit" {
            break;
        }

        log::info!("User input: {}", input);
        let config = crate::config::load_config()?;
        let messages = vec![
            Message {
                role: "system".to_string(),
                content: config.system_content.to_string(),
            },
            Message {
                role: "user".to_string(),
                content: input.to_string(),
        }];

        match send_chat_request(messages).await {
            Ok(response) => {
                log::info!("API response received");
                // println!("Response: {}", response);
                if let Ok(parsed_response) = serde_json::from_str::<serde_json::Value>(&response) {
                    if let Some(choices) = parsed_response.get("choices") {
                        if let Some(first_choice) = choices.get(0) {
                            if let Some(message) = first_choice.get("message") {
                                if let Some(content) = message.get("content") {
                                    let answer = content.to_string().replace("\\n", "\n");
                                    log::info!("{}",answer);
                                    println!("==============回复==============:\n {}", answer);
                                }
                            }
                        }
                    }
                }
            }
            Err(e) => {
                log::error!("API request failed: {}", e);
                eprintln!("Error: {}", e);
            }
        }
    }

    log::info!("Application finished");
    Ok(())
}